/**
 * Jun 27, 2014 9:57:58 AM
 */
package elitech.vietnam.myfashion.fragment;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParserException;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import elitech.vietnam.myfashion.MainActivity;
import elitech.vietnam.myfashion.R;
import elitech.vietnam.myfashion.entites.Notify;
import elitech.vietnam.myfashion.extend.AsyncTask;
import elitech.vietnam.myfashion.extend.NotifyArrayAdapter;
import elitech.vietnam.myfashion.wsclient.Service;

/**
 * @author Cong
 *
 */
public class NotificationsFragment extends Fragment implements View.OnClickListener, OnScrollListener {

	MainActivity mActivity;
	
	ListView mListView;
	NotifyArrayAdapter mAdapter;
	LinearLayout mLayTitle;
	ImageButton mFloatMenu;
	TextView mNoData;
	
	View mLoading;
	
	boolean isLoading = false, isEnd = false;
	
	public NotificationsFragment() {}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mActivity = (MainActivity) getActivity();
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.notifications, container, false);
		mLoading = inflater.inflate(R.layout.notiloading, null);
		
		mLayTitle = (LinearLayout) view.findViewById(R.id.main_menu);
		mListView = (ListView) view.findViewById(R.id.notify_lvNotifications);
		mFloatMenu = (ImageButton) view.findViewById(R.id.btnFloatMenu);
		mNoData = (TextView) view.findViewById(R.id.notify_txtNodata);

		mListView.addFooterView(mLoading);
		
		mAdapter = new NotifyArrayAdapter(mActivity, R.layout.notification_list_item, mActivity.mListNotifications);
		mListView.setAdapter(mAdapter);
		
		mFloatMenu.setOnClickListener(this);
		mLayTitle.setOnClickListener(this);
		
		if (mActivity.mUser != null && mActivity.mListNotifications.size() < 20 && !isEnd) {
			isLoading = true;
			new GetNotifications().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
		}

		mListView.setOnScrollListener(this);
		return view;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.main_menu:
		case R.id.btnFloatMenu:
			mActivity.callMenu();
			break;
		default:
			break;
		}
	}
	
	
	
	class GetNotifications extends AsyncTask<Integer, Integer, Boolean> {
		ArrayList<Notify> rs = new ArrayList<>();
		@Override
		protected Boolean doInBackground(Integer... params) {
			try {
				rs = new Service().getNotifications(mActivity.mUser.Id, 0, 20);
			} catch (IOException | XmlPullParserException e) {
				e.printStackTrace();
				return false;
			}
			return true;
		}
		@Override
		protected void onPostExecute(Boolean result) {
			isLoading = false;
			if (!isVisible())
				return;
			if (!result) {
			} else if (rs == null || rs.isEmpty()){
				mListView.setVisibility(View.GONE);
				mNoData.setVisibility(View.VISIBLE);
			} else {
				Log.w("GetNotifications", "onPostExecute " + mActivity.mUser.Id);
				mActivity.mListNotifications.clear();
				mActivity.mListNotifications.addAll(rs);
				mNoData.setVisibility(View.GONE);
				// End list, no need to load anymore
				if (rs.size() < 20 && rs.size() > 0) {
					isEnd = true;
					mListView.removeFooterView(mLoading);
				}
				mAdapter.notifyDataSetChanged();
			}
		}
	}

	class GetMoreData extends AsyncTask<Integer, Integer, Boolean> {
		List<Notify> rs = new ArrayList<>();
		@Override
		protected Boolean doInBackground(Integer... params) {
			try {
				rs = new Service().getNotifications(mActivity.mUser.Id, mActivity.mListNotifications.size(), 20);
			} catch (IOException | XmlPullParserException e) {
				e.printStackTrace();
				return false;
			}
			return true;
		}
		@Override
		protected void onPostExecute(Boolean result) {
			Log.w("GetMoreData", "onPostExecute");
			isLoading = false;
			if (!isVisible())
				return;
			if (!result) {
				new GetMoreData().execute();
			} else if (rs == null || rs.isEmpty() || (rs.size() > 0 && rs.size() < 20)){
				// End list, no need to load anymore
				isEnd = true;
				mListView.removeFooterView(mLoading);
			} else {
				mActivity.mListNotifications.addAll(rs);
			}
			mAdapter.notifyDataSetChanged();
		}
	}


	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
	}
	@Override
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
		if (mListView.getAdapter().getCount() == 0 || isEnd)
	        return ;
	     
	    int l = visibleItemCount + firstVisibleItem;
	    if (l >= totalItemCount && !isLoading && mActivity.mUser != null) {
	        isLoading = true;
	        new GetMoreData().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	    }
	}
}
